﻿using System;
using System.Web;
using Inscriptionem.Extensions;
using Inscriptionem.ORM;
using Inscriptionem.Services;

namespace Inscriptionem.MVC.Logging
{
    public class RequestLoggerModule : IHttpModule
    {
        #region Static Members

        protected static string[] ExceptionExtensionItems = new string[] {".css", ".js", ".jpeg", ".jpg", ".jpe", ".gif", ".bmp", ".png", ".svg", ".rar", ".zip", ".exe", ".doc", ".docx", ".csv", ".xls", ".xlsx", ".xml", ".pdf", ".djvu"};
        #endregion
        public void Dispose()
        {

        }

        public void Init(HttpApplication context)
        {
            // TODO check configuration, if logging disabled
            context.BeginRequest += new EventHandler(context_BeginRequest);
        }

        void context_BeginRequest(object sender, EventArgs e)
        {
            if (!InstallService.IsDBAvailableAndCorrect)
            {
                return;
            }

            HttpApplication application = (HttpApplication) sender;
            var request = application.Request;

            // Skip files
            string url = request.Url.ToString().ToLower();
            if (url.EndsWithAny(ExceptionExtensionItems))
            {
                return;
            }

            try
            {
                DB db = new DB();
                db.LogRequests.AddObject(new LogRequest()
                                             {
                                                 URL = request.Url.ToString(),
                                                 ReferrerURL = request.UrlReferrer == null ? string.Empty : request.UrlReferrer.ToString(),
                                                 UserAgent = request.UserAgent,
                                                 UserHostAddress = request.UserHostAddress,
                                                 CreatedDate = DateTime.Now
                                             });
                db.SaveChanges();
            }
            catch (Exception)
            {
            }
        }
    }
}